class MyBlockingQueue{
    //浪费一个空间，来区分满与空
    private volatile String[] data = new String[2 + 1];
    private volatile int head = 0;
    private volatile int tail = 0;


    public void put(String s) throws InterruptedException {
        synchronized (this){
            while((tail + 1) % data.length == head){
                //如果队列满了，就会阻塞
                this.wait();
            }
            //队列不满，插入元素
            data[tail] = s;
            tail = (tail + 1) % data.length;
            //唤醒take中wait的线程
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this){
            while(head == tail){
                //如果队列为空，阻塞等待
                this.wait();
            }
            String ret = data[head];
            head = (head + 1) % data.length;
            //唤醒put中wait的线程
            this.notify();
            return ret;
        }
    }
}

public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            try {
                myBlockingQueue.put("1");
                myBlockingQueue.put("1");
                myBlockingQueue.put("1");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        Thread.sleep(100);

        Thread t2 = new Thread(() -> {
            try {
                System.out.println(myBlockingQueue.take());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t2.start();
    }
}
